package LeetCode_Stack;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:最小栈问题
 * User: 阿宾
 * Date: 2024-11-14
 * Time: 09:39
 */
class MinStack {
    private Stack<Integer> stack;
    private Stack<Integer> minstack;

    public MinStack() {
        this.stack = new Stack<>();
        this.minstack = new Stack<>();
    }

    public void push(int val) {
        stack.push(val);
        if(minstack.empty()){
            minstack.push(val);
        }else {
            if(val <= minstack.peek()){
                minstack.push(val);
            }
        }
    }

    public void pop() {
        if(!stack.empty()){
            int ret = stack.pop();
            if(ret == minstack.peek()){
                minstack.pop();
            }
        }
    }

    public int top() {
        if(!stack.empty()){
            return stack.peek();
        }
        return -1;//题中已经说明栈不会为空，这句只是为了代码语法不报错
    }

    public int getMin() {
        if(!stack.empty()){
            return minstack.peek();
        }
        return -1;//题中已经说明栈不会为空，这句只是为了代码语法不报错
    }
}
public class Demo4 {

    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(-2);
        minStack.push(0);
        minStack.push(-2);
        minStack.push(9);
        minStack.push(-10);

        System.out.println(minStack.getMin());
        minStack.pop();
        System.out.println(minStack.top());
        System.out.println(minStack.getMin());


    }
}
